<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="请按规定添加商品信息" type="info" center show-icon></el-alert>
      <!-- step步骤栏 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" :align-center="true">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- Tab栏切换区域 -->
      <el-form :model="basicInfo" :rules="basicInfoRules" ref="basicInfoRef">
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabsBtn"
        >
          <!-- 基本信息区域 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="basicInfo.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="basicInfo.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="basicInfo.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="basicInfo.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="basicInfo.goods_cat"
                :options="cateList"
                expandTrigger="hover"
                :props="props"
                @change="handleCatesChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数区域 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item1.attr_name"
              v-for="item1 in manyTableData"
              :key="item1.attr_id"
            >
              <el-checkbox-group v-model="item1.attr_vals">
                <el-checkbox
                  v-for="(item2,index) in item1.attr_vals"
                  :key="index"
                  :label="item2"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性区域 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item3.attr_name"
              v-for="item3 in onlyTableData"
              :key="item3.attr_id"
            >
              <el-input v-model="item3.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片区域 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 商品图片上传
            :action:指定图片上传api接口
            :on-preview ： 当点击图片时会触发该事件进行预览操作,处理图片预览
            :on-remove : 当用户点击图片右上角的X号时触发执行
            :on-success：当用户点击上传图片并成功上传时触发
             list-type ：设置预览图片的方式
            :headers ：设置上传图片的请求头-->
            <el-upload
              :action="uploadUrl"
              :on-preview="clickToPreview"
              :on-remove="clickToDelete"
              :on-success="clickToUpload"
              list-type="picture"
              :headers="headersToken"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容区域 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本区域 -->
            <quill-editor v-model="basicInfo.goods_introduce" class="minHeight"></quill-editor>
            <el-button type="primary" @click="addGoodsBtnInfo" class="addGoodsBtnInfo">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog title="图片预览" :visible.sync="PreviewVisible" width="50%">
      <img :src="previewUrl" class="imgWidth" />
    </el-dialog>
    <!-- 添加商品完成的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="LastViewVisible"
      width="50%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <h3>添加成功，请等待跳转......5秒后自动跳转到商品列表！</h3>
    </el-dialog>
  </div>
</template>

<script>
// 引入lodash依赖
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: name,
      basicInfo: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pictures: [],
        goods_introduce: '',
        attrs:[]
      },
      basicInfoRules: {
        goods_name: [
          { required: true, message: '请输入商品名称！', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格！', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量！', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量！', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类！', trigger: 'blur' },
        ],
      },
      // 分类数据
      cateList: [],
      // 配置级联菜单中数据如何展示
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 动态参数
      manyTableData: [],
      // 静态属性
      onlyTableData: [],
      // 上传图片接口
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片请求头
      headersToken: { Authorization: window.sessionStorage.getItem('token') },
      // 图片预览是否显示
      PreviewVisible: false,
      // 预览图片地址
      previewUrl: '',
      LastViewVisible: false,
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表数据
    async getCateList() {
      // 发送请求获取分类数据
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 触发级联选择器时的事件 只能选择第三级
    handleCatesChange() {
      if (this.basicInfo.goods_cat.length !== 3) {
        this.basicInfo.goods_cat = []
        return
      }
    },
    // tab栏切换触发的切换前事件
    //在tab栏切换之前触发，两个形参为切换前，后的tab栏name
    beforeTabLeave(newActiveName, oldActiveName) {
      if (oldActiveName === '0') {
        if (this.basicInfo.goods_cat.length !== 3) {
          this.$message.error('商品分类不能为空！')
          return false
        } else if (this.basicInfo.goods_name.trim() === '') {
          this.$message.error('商品名称不能为空！')
          return false
        } else if (this.basicInfo.goods_price === '') {
          this.$message.error('商品价格不能为空！')
          return false
        } else if (this.basicInfo.goods_weight === '') {
          this.$message.error('商品重量不能为空！')
          return false
        } else if (this.basicInfo.goods_number === '') {
          this.$message.error('商品数量不能为空！')
          return false
        }
      }
    },
    // tab切换时触发
    async tabsBtn() {
      // 当点击到商品参数的时候触发
      if (this.activeIndex === '1') {
        // 发送请求获取动态商品参数的数据
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 将数据存到data之前进行转换数组
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' },
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.onlyTableData = res.data
      }
    },
    // 点击预览图片
    clickToPreview(file) {
      // file是指被上传的图片本身
      this.previewUrl = file.response.data.url
      this.PreviewVisible = true
    },
    // 点击成功上传图片
    clickToUpload(res) {
      this.basicInfo.pictures.push({ pic: res.data.tmp_path })
    },
    // 点击删除图片
    clickToDelete(file) {
      // 点击删除的图标执行 将前端data里面的pictrues删除 根据点击的预览图片里面的临时URL找到该index 然后删除图片数据
      // 从被删除的图片中获取到临时地址
      const path = file.response.data.tmp_path
      // 根据这个临时地址找到data里面存的临时地址的下标index
      const index = this.basicInfo.pictures.findIndex((item) => {
        return item.pic === path
      })
      // 根据根据下标删除data中的数据
      this.basicInfo.pictures.splice(index, 1)
    },
    // 点击添加商品按钮
    addGoodsBtnInfo() {
      // 对所有数据进行预验证
      this.$refs.basicInfoRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请填写必要的表单项！')
        // 将basicInfo进行深拷贝
        let basicInfoCloned = _.cloneDeep(this.basicInfo)
        // 将goods_cat转换成逗号隔开的字符串
        basicInfoCloned.goods_cat = basicInfoCloned.goods_cat.join(',')
        // 处理attrs数组 将动态参数和静态属性的值添加到attrs中去
        this.manyTableData.forEach((item) => {
          this.basicInfo.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' '),
          })
        })
        this.onlyTableData.forEach((item) => {
          this.basicInfo.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          })
        })
        // 因为最终提交的数据是克隆后的 所以全部要给到他
        basicInfoCloned.attrs = this.basicInfo.attrs
        console.log(basicInfoCloned);
        // 发送请求添加商品
        const { data: res } = await this.$http.post('goods', basicInfoCloned)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.LastViewVisible = true
        // 让步骤高亮到完成
        this.activeIndex = '5'
        // 编程式导航跳转到商品列表
        setTimeout(() => {
          this.$router.push('/goods')
        }, 5000)
      })
    },
  },
  computed: {
    // 计算出cateId
    cateId() {
      if (this.basicInfo.goods_cat.length === 3) {
        //
        return this.basicInfo.goods_cat[2]
      }
      return null
    },
  },
}
</script>

<style lang="less" scoped>
.el-form-item {
  margin-bottom: 20px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.imgWidth {
  width: 100%;
}
</style>